//
//  StoresViewController.m
//  House
//
//  Created by 张垚 on 16/6/28.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "StoresViewController.h"
#import "SearchHouseViewController.h"
#import "BaseNavigationBar.h"
#import "MySearchBar.h"
#import "AreaSelectedLeftTableViewCell.h"
#import "AreaSelectedRightTableViewCell.h"
#import "StoreDetailView.h"
#import "StoresListModel.h"
#import "BaseTitleNavigationBar.h"

@interface StoresViewController ()<UITableViewDelegate, UITableViewDataSource>
//两个tableview
@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;
//弹出背景框view属性
@property (nonatomic, strong) UIView *backgroundView;
//左右tableview数据
@property (nonatomic, strong) NSArray *leftDataArr;
@property (nonatomic, strong) NSMutableArray *rightDataArr;
//门店详情
@property (nonatomic, strong) NSDictionary *storeDetailDic;

@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
@end
//门店接口
static NSString *urlStr = @"http://aizufang.hrbzjwl.com/tp/api.php/Mendian/index";


@implementation StoresViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    //布局不受系统控制
    self.automaticallyAdjustsScrollViewInsets = NO;
    //取出区域
//    YTKKeyValueStore *areaStore = [[YTKKeyValueStore alloc] initDBWithName:dataBaseName];
//    _leftDataArr = [areaStore getObjectById:[[NSUserDefaults standardUserDefaults] objectForKey:cityID] fromTable:tableName];
    [self handleData];
    //初始化
    _rightDataArr = [NSMutableArray array];
    _storeDetailDic = [NSDictionary dictionary];
    // Do any additional setup after loading the view.
    //tableview
    [self initTableViews];
    [self initNavigationBar];
    //默认选中第一个
//    [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    //右边tableview数据请求
    [self getRightTableData];
    
}
#pragma mark - 数据请求

//区域数据获取
- (void)handleData {
    _leftDataArr = [NSArray array];
    [NetRequest getInformationWithGetMethodWithUrl:@"http://aizufang.hrbzjwl.com/tp/api.php/Index/qu" success:^(NSURLSessionDataTask *task, id responseObject) {
        _leftDataArr = responseObject;
        [_leftTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
    
}



//右边tableview数据请求
- (void)getRightTableData {
    [NetRequest getWithURLString:urlStr parameters:@{@"areaid" :[[NSUserDefaults standardUserDefaults] objectForKey:cityID]} progress:^(NSProgress *progress) {
        
    } success:^(id response) {
        //遍历右边数据 根据左边区域id来区分 装入不同的数组 进行显示
        for (int i = 0; i < _leftDataArr.count; i++) {
            //给一个初始值 防止添加为空 发生crash
            NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1", nil];
            NSDictionary *areaDic = _leftDataArr[i];
            for (NSDictionary *dic in response[@"mendian"]) {
                if ([dic[@"areaid"] isEqualToString:areaDic[@"areaid"]]) {
                    [array addObject:dic];
                }
                if (array.count >= 2) {
                    [array removeObject:@"1"];
                }
        }
            [_rightDataArr addObject:array];
        }
        [_rightTableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}


#pragma mark - 导航栏搜索
/* 重写父类方法 */
//- (void)initNavigationBar {
//    [super initNavigationBar];
//    self.myBar.searchBar.textFiled.placeholder = @"请输入门店名";
//    [self.myBar.searchBar.textFiled setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
//    UITapGestureRecognizer *popTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pop:)];
//    [self.myBar.leftView addGestureRecognizer:popTap];
//    UITapGestureRecognizer *pushSearchHouseTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(push)];
//    [self.myBar.searchBar addGestureRecognizer:pushSearchHouseTap];
//}
//自定义导航栏
- (void)initNavigationBar {
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:@"直营店"];
    [self.view addSubview:_myBar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pop:)];
    [_myBar.leftView addGestureRecognizer:tap];
}
//返回点击事件
- (void)pop:(UITapGestureRecognizer *)tap {
    [self.navigationController popViewControllerAnimated:YES];
}

/* 点击搜索栏 跳转页面进行搜索 */
- (void)push {
    SearchHouseViewController *searchVC = [[SearchHouseViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark - tableview
//创建tableview
- (void)initTableViews {
    CGFloat height = kScreenHeight - kNaviBarHeight;
    CGFloat width = kScreenWidth / 3.0f;
    //left
    self.leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviBarHeight, width , height) style:UITableViewStylePlain];
    [self.view addSubview:_leftTableView];
    _leftTableView.delegate = self;
    _leftTableView.dataSource = self;
    _leftTableView.bounces = NO;
    _leftTableView.tableFooterView = [UIView new];
    [_leftTableView registerClass:[AreaSelectedLeftTableViewCell class] forCellReuseIdentifier:NSStringFromClass([AreaSelectedLeftTableViewCell class])];
    //right
    self.rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(width, kNaviBarHeight, width * 2, height) style:UITableViewStylePlain];
    [self.view addSubview:_rightTableView];
    _rightTableView.delegate = self;
    _rightTableView.dataSource = self;
    _rightTableView.tableFooterView = [UIView new];
    _rightTableView.bounces = NO;
    [_rightTableView registerClass:[AreaSelectedRightTableViewCell class] forCellReuseIdentifier:NSStringFromClass([AreaSelectedRightTableViewCell class])];
    
}
#pragma mark tableviwe datasouce delegate
//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_leftTableView]) {
        return 1;
    } else {
        return _leftDataArr.count;
    }
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_leftTableView]) {
        return _leftDataArr.count;
    } else {
        if (_rightDataArr.count > 0 ) {
            NSArray *arr = _rightDataArr[section];
            if ([arr containsObject:@"1"]) {
                return 0;
            }else {
                return arr.count;
            }
        }else {
            return 0;
        }
    }
    
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AreaSelectedLeftTableViewCell *leftCell = [_leftTableView dequeueReusableCellWithIdentifier:NSStringFromClass([AreaSelectedLeftTableViewCell class])];
    AreaSelectedRightTableViewCell *rightCell = [_rightTableView dequeueReusableCellWithIdentifier:NSStringFromClass([AreaSelectedRightTableViewCell class])];
    rightCell.selectionStyle = UITableViewCellSelectionStyleNone;
    leftCell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([tableView isEqual:_leftTableView]) {
        NSDictionary *dic = _leftDataArr[indexPath.row];
        leftCell.nameLabel.text = dic[@"areaname"];
        return leftCell;
    } else {
        NSArray *arr = _rightDataArr[indexPath.section];
        NSDictionary *dic = arr[indexPath.row];
        StoresListModel *model = [StoresListModel modelWithDic:dic];
        rightCell.nameLabel.text = model.company;
        rightCell.positionLabel.text = model.addr;
        return rightCell;
    }
}

//section标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_leftTableView]) {
        return nil;
    } else {
        NSDictionary *dic = _leftDataArr[section];
        return dic[@"areaname"];
    }
}
//header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_leftTableView]) {
        return 0;
    } else {
        return 25;
    }
}
//行高

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_leftTableView]) {
        return 44;
    } else {
        return 70;
    }
}
//cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_leftTableView]) {
        AreaSelectedLeftTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.nameLabel.textColor = KNaviBackColor;
        NSArray *arr = _rightDataArr[indexPath.row];
        if (arr.count > 0) {
            if ([arr containsObject:@"1"]) {
                
            }else {
                 [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
          
        }
    }
    //点击右边cell 弹出门店信息
    if ([tableView isEqual:_rightTableView]) {
        NSArray *arr = _rightDataArr[indexPath.section];
        NSDictionary *dic = arr[indexPath.row];
        StoresListModel *model = [StoresListModel modelWithDic:dic];
        [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/api.php/Mendian/chuang" parameters:@{@"userid": model.userid} progress:^(NSProgress *progress) {
            
        } success:^(id response) {
            _storeDetailDic = response[@"chuang"];
            [self alertDetailViewWithInfo:_storeDetailDic];
            [_rightTableView reloadData];
        } failure:^(NSError *error) {
            
        }];
           }
}
//cell未被点击事件
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_leftTableView]) {
        AreaSelectedLeftTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.nameLabel.textColor = [UIColor blackColor];
    }
}
//弹框信息
- (void)alertDetailViewWithInfo:(NSDictionary *)dic {
    _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:_backgroundView];
    _backgroundView.backgroundColor = [UIColor colorWithRed:0.2268 green:0.2268 blue:0.2268 alpha:0.8];
    
    StoreDetailView *selectView = [[StoreDetailView alloc] init];
    selectView.backgroundImageView.image = [UIImage imageNamed:@"agentBackImage"];
    selectView.addressLabel.text = dic[@"addr"];
    //门店位置 拨打电话 点击事件添加
    [selectView.mapButton setTitle:dic[@"company"] forState:UIControlStateNormal];
    //[selectView.mapButton addTarget:self action:@selector(locationShow) forControlEvents:UIControlEventTouchUpInside];
    [selectView.numberButton setTitle:dic[@"mobile"] forState:UIControlStateNormal];
    [selectView.numberButton addTarget:self action:@selector(callPhone:) forControlEvents:UIControlEventTouchUpInside];
    
    [_backgroundView addSubview:selectView];
    UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backgroundView addSubview:removeButton];
    //布局
    [selectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(260, 320));
        make.centerX.equalTo(_backgroundView.mas_centerX);
        make.centerY.equalTo(_backgroundView.mas_centerY);
    }];
    [removeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(selectView.mas_top);
        make.size.mas_equalTo(CGSizeMake(25, 40));
        make.right.equalTo(selectView.mas_right).offset(-5);
    }];
    [removeButton setImage:[UIImage imageNamed:@"removeButton"] forState:UIControlStateNormal];
    [removeButton addTarget:self action:@selector(remove) forControlEvents:UIControlEventTouchUpInside];
    [self shakeToShow:_backgroundView];
  
}

#pragma mark - 地图显示 拨打电话 点击事件
//地图显示
- (void)locationShow {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"地图显示" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *callAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:callAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
//拨打电话
- (void)callPhone:(UIButton *)button {
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",button.titleLabel.text];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

//点击右边cell 点击放大图片动画效果
- (void)shakeToShow:(UIView *)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.25;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}
//轮播部分 点击移除视图 图片正常显示
- (void)remove {
    [UIView animateWithDuration:0.25 animations:^{
        [_backgroundView removeFromSuperview];
    }];
    
}



#pragma mark - 滑动tableview
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    if ([scrollView isEqual:_rightTableView]) {
//        AreaSelectedRightTableViewCell *cell = _rightTableView.visibleCells.firstObject;
//        NSIndexPath *indexPath = [_rightTableView indexPathForCell:cell];
//        //NSIndexPath *leftIndex = [NSIndexPath indexPathForRow:indexPath.section inSection:0];
//        [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
////        AreaSelectedLeftTableViewCell *leftCell = [_leftTableView cellForRowAtIndexPath:leftIndex];
////        leftCell.nameLabel.textColor = [UIColor redColor];
//    }
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
